package com.bao.auth.server.biz.service.auth.impl;

import com.bao.auth.dto.auth.ResourceQueryDTO;
import com.bao.auth.entity.auth.Resource;
import com.bao.auth.server.biz.dao.auth.ResourceMapper;
import com.bao.auth.server.biz.service.auth.ResourceService;
import com.bao.core.base.id.CodeGenerate;
import com.bao.core.exception.BizException;
import com.bao.core.utils.StrHelper;
import com.bao.databases.mybatis.conditions.Wraps;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private CodeGenerate codeGenerate;
    
    @Override
    public List<Resource> findVisibleResource(ResourceQueryDTO resource) {
        List<Resource> visibleResource = baseMapper.findVisibleResource(resource);
        return visibleResource;
    }

    
    @Override
    public void removeByMenuId(List<Long> menuIds) {
        //根据菜单id查询资源信息
        List<Resource> resources = super.list(Wraps.<Resource>lbQ().in(Resource::getMenuId, menuIds));
        if(resources.isEmpty()) {
            return;
        }
        //提出资源信息，并删除
        List<Long> ids = resources.stream().mapToLong(Resource::getId).boxed().collect(Collectors.toList());
        super.removeByIds(ids);
    }

    @Override
    public List<Long> findMenuIdByResourceId(List<Long> resourceIds) {
        return baseMapper.findMenuIdByResourceId(resourceIds);
    }

    /**
     * 重写mybatisplus生成的save方法
     * @param resource 实体对象
     * @return
     */
    @Override
    public boolean save(Resource resource) {
        //当菜单编码为空时，使用编码生成器生成一个编码
        resource.setCode(StrHelper.getOrDef(resource.getCode(),codeGenerate.next()));
        //判断当前的code是否在数据库中存在
        if (super.count(Wraps.<Resource>lbQ().eq(Resource::getCode, resource.getCode())) > 0) {
            throw BizException.validFail("编码[%s]重复", resource.getCode());
        }
        //判断编码没有问题后，调用原本的保存方法
        super.save(resource);
        return true;
    }
}
